<template>
  <div style="margin: 15px" class="pay">
    <el-card>
      <div slot="header">
        <span
          style="
            margin-bottom: 8px;
            display: flex;
            align-items: center;
            font-size: 18px;
            padding-bottom: 2px;
          "
        >
          <img
            src="@/assets/img/txjl.png"
            style="width: 20px; margin-right: 5px"
          />
          提现记录</span
        >
        <div class="xhxBox"></div>
      </div>
      <!-- 查询表单 -->
      <div style="margin: 20px 0px 0px -10px">
        <el-form :inline="true" label-position="right" label-width="90px">
          <el-form-item label="提现时间">
            <el-date-picker
              v-model="formData.field103"
              type="datetimerange"
              align="right"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="width: 250px; margin-right: 30px"
              :default-time="['00:00:00', '23:59:59']"
              value-format="yyyy-MM-dd HH:mm:ss"
         
            >
            </el-date-picker>
            <!-- <el-date-picker
              v-model="formData.field103"
              style="width: 200px; margin-right: 30px"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="至"
              clearable
              :picker-options="pickerOptions0"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            >
            </el-date-picker> -->
          </el-form-item>

          <!-- <el-form-item label="预留手机号">
            <el-input
              v-model="formData.mobile"
                placeholder="请输入预留手机号"
                :maxlength="11"
                show-word-limit
                clearable
              style="margin-right: 30px;width:200px"
            ></el-input>
          </el-form-item> -->

          <el-form-item label="提现状态">
            <el-select
              v-model="formData.field107"
              placeholder="请选择提现状态"
              clearable
              filterable
              style="margin-right: 30px; width: 250px"
            >
              <el-option
                v-for="(item, index) in field107Options"
                :key="index"
                :label="item.label"
                :value="item.value"
                :disabled="item.disabled"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="" style="margin-left: 110px">
            <el-button
              icon="el-icon-refresh"
              style="background: #eeeeee; color: #6396f4; font-weight: bold"
              @click="resetQuery"
              >重置
            </el-button>
            <el-button type="primary" icon="el-icon-search" @click="getList(1)"
              >搜索</el-button
            >
          </el-form-item>
        </el-form>
        <!-- <div style="display:flex;justify-content:center">
           <el-button
              icon="el-icon-refresh"
              style="background: #eeeeee; color: #6396f4; font-weight: bold"
              @click="resetForm"
              >重置
            </el-button>
            <el-button type="primary" icon="el-icon-search" @click="submitForm"
              >搜索</el-button
            >
        </div> -->
      </div>

      <el-divider></el-divider>
      <!-- 数据展示 -->
      <el-card style="height: 150px; margin-top: 10px">
        <div style="display: flex; height: 100%">
          <div class="pay-item">
            <div class="pay-value" style="color: red">
              <span>￥</span>
              <!-- {{ CardData.totalWithdrawalAmount || 0 }} -->
              {{ CardData.totalAmount || 0 }}
            </div>
            <div class="pay-label">提现申请金额(元)</div>
          </div>
          <div class="pay-item">
            <div class="pay-value">
              <span>￥</span>
              <!-- {{ CardData.alipayTotalWithdrawalAmount || 0}} -->
              {{ CardData.realityAmount || 0 }}
            </div>
            <div class="pay-label">实际到账金额(元)</div>
          </div>
          <div class="pay-item">
            <div class="pay-value">
              <span>￥</span>
              <!-- {{CardData.bankCardTotalWithdrawalAmount || 0}} -->
              {{ CardData.serviceAmount || 0 }}
            </div>
            <div class="pay-label">提现手续费(元)</div>
          </div>

          <div class="pay-item">
            <div class="pay-value value-color">
              <span>￥</span>
              {{ amountMoney || 0 }}
            </div>
            <div class="pay-label">我的余额(元)</div>
            <div style="margin-top: 5px">
              <el-button @click="withdrawal" type="primary" size="mini"
                >提现</el-button
              >
            </div>
          </div>
        </div>
      </el-card>
      <el-divider></el-divider>
      <!-- tab-表格 -->
      <div style="margin: 20px 0px">
        <div class="exportButton">
          <el-button
            icon="el-icon-upload2"
            @click="withdrawExport"
            style="margin-bottom: 10px; background: #f5f5f5"
            >导出</el-button
          >
        </div>
        <el-table
          :data="roleList"
          :header-cell-style="{
            background: '#FAFAFA',
            color: 'black',
            'font-size': 15 + 'px',
            'text-align': 'center',
          }"
        >
          <el-table-column
            label="提现时间"
            prop="createTime"
            align="center"
            width="150"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.createTime || "暂无" }}</span>
            </template>
          </el-table-column>
          <!-- <el-table-column label="提现账户" prop="userName" align="center" /> -->

          <!-- <el-table-column label="昵称" prop="nickName" align="center" /> -->

          <el-table-column
            label="提现方式"
            prop="withdrawalAccountType"
            align="center"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              <!-- <span v-show="scope.row.withdrawalAccountType == 'ALIPAYACCOUNTBOOK'">记账本</span> -->
              <span v-show="scope.row.withdrawalAccountType == 'BANKCARD'"
                >银行卡</span
              >
              <span v-show="scope.row.withdrawalAccountType == 'ALIPAY'"
                >支付宝</span
              >
            </template>
          </el-table-column>

          <!-- <el-table-column
            label="支付名称"
            prop="signAccountName"
            align="center"
            :show-overflow-tooltip="true"
           /> -->

          <el-table-column
            label="提现金额/元"
            prop="amount"
            align="center"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="收款户名"
            prop="withdrawalAccountName"
            align="center"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.withdrawalAccountName || "暂无" }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="收款账户"
            prop="withdrawalAccountNumber"
            align="center"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <span>{{ scope.row.withdrawalAccountNumber || "暂无" }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="身份证号"
            prop="withdrawalIdCard"
            align="center"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <span>{{ scope.row.withdrawalIdCard || "暂无" }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="预留手机号"
            prop="withdrawalPhoneNumber"
            align="center"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <span>{{ scope.row.withdrawalPhoneNumber || "暂无" }}</span>
            </template>
          </el-table-column>

          <!-- <el-table-column label="身份证号" prop="idCard" align="center" show-overflow-tooltip>
            <template slot-scope="scope">
              <span>{{ scope.row.idCard || "暂无" }}</span>
            </template>
          </el-table-column> -->
          <!-- <el-table-column label="预留手机号" prop="phone" align="center" show-overflow-tooltip>
            <template slot-scope="scope">
              <span>{{ scope.row.phone || "暂无" }}</span>
            </template>
          </el-table-column> -->
          <el-table-column label="提现状态" align="center" prop="status">
            <template slot-scope="scope">
              <span v-show="scope.row.status == 'SUCCESS'">成功</span>
              <span v-show="scope.row.status == 'FAIL'">失败</span>
              <span v-show="scope.row.status == 'WATTING'">转帐中</span>
              <span v-show="scope.row.status == 'INIT'">初始化</span>
            </template>
          </el-table-column>
          <el-table-column
            label="提现信息"
            prop="message"
            align="center"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <span>{{ scope.row.callbackMessage || "暂无" }}</span>
              <!-- <span>{{ scope.row.callbackMessage}}</span> -->
            </template>
          </el-table-column>
          <el-table-column label="手续费" prop="serviceAmount" align="center" />
          <el-table-column
            label="实际到账金额"
            prop="realityAmount"
            align="center"
          />
        </el-table>
      </div>
      <pagination
        style="margin: 0px 0px 50px 0px"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
    <!-- 公告弹窗 -->
    <Dialog
      ref="mychild"
      @AddAnnouncement="AddAnnouncement"
      :uelLocation="uelLocation"
    />
  </div>
</template>

<script>
import { getInfo, getIdentityAndTopId } from "@/api/login.js";
import Dialog from "@/views/components/Dialog.vue";
import {
  selectCapWithdrawalRecordList,
  CapWithdrawalRecordStatistics,
  exportXls,
  selectCapUserWalletById,
  selectTransactionRecordPaging,
} from "@/api/finance/index.js";
export default {
  data() {
    return {
      pickerOptions0: {
        disabledDate(time) {
          return time.getTime() > Date.now() - 8.64e6;
        },
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
            disabledDate(time) {
              return time.getTime() > Date.now();
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
            disabledDate(time) {
              return time.getTime() > Date.now();
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
            disabledDate(time) {
              return time.getTime() > Date.now();
            },
          },
        ],
      },
      uelLocation: "",
      //我的余额
      amountMoney: "",
      witStatus: [
        { label: "失败", value: "FAIL" },
        { label: "成功", value: "SUCCESS" },
        // {label: "转帐中",
        //   value: "转帐中"},
      ],
      formData: {
        field103: [],
        field105: undefined,
        mobile: "",
        field104: undefined,
        field106: undefined,
        field107: undefined,
        field108: undefined,
        field109: undefined,
        field110: undefined,
        field111: undefined,
      },
      searchrules: {
        field103: [],
        field105: [],
        mobile: [
          {
            pattern: /^1(3|4|5|7|8|9)\d{9}$/,
            message: "手机号格式错误",
            trigger: "blur",
          },
        ],
        field104: [],
        field106: [],
        field107: [],
        field108: [],
        field109: [],
        field110: [],
        field111: [
          {
            pattern:
              /^([1-6][1-9]|50)\d{4}(18|19|20)\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
            message: "身份证格式错误",
            trigger: "blur",
          },
        ],
      },
      field105Options: [
        {
          label: "记账本",
          value: 0,
        },
        {
          label: "银行卡",
          value: 1,
        },
        {
          label: "支付宝",
          value: 2,
        },
      ],
      field107Options: [
        {
          label: "全部",
          value: undefined,
        },
        {
          label: "成功",
          value: "SUCCESS",
        },
        {
          label: "失败",
          value: "FAIL",
        },
      ],
      //

      // ..卡片总数据
      CardData: {},
      rules: {
        money: [{ required: true, message: "请输入提现金额", trigger: "blur" }],
        region: [
          { required: true, message: "请选择提现类型", trigger: "change" },
        ],
        monetUser: [
          { required: true, message: "请选择提现账号", trigger: "blur" },
        ],
      },
      // ..提现账号下拉框数据
      monetUser: [],
      // 用户ID
      userId: 0,

      // 时间
      dateRange: [],

      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 分页总条数
      total: 0,
      // 收入表格数据
      noticeList: [],
      // 状态数据字典
      typeOptions: [
        {
          dictLabel: "分润",
          dictValue: 0,
        },
        {
          dictLabel: "佣金",
          dictValue: 1,
        },
      ],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        // 收入类型
        amountType: "",
        // 时间
        // dateRange: "",
      },
      roleList: [],
    };
  },
  async mounted() {
    this.defaultDate()
    this.formData.field103[0] =
      this.moment().format("YYYY") +
      "-" +
      this.moment().format("MM") +
      "-" +
      "01" +
      " " +
      "00:00:00";
    this.formData.field103[1] =
      this.moment().format("YYYY-MM-DD") + " " + "23:59:59";

    const userID = sessionStorage.getItem("userID");
    this.userId = userID - 0;
    this.getList2();
    //获取是租户还是用户还是平台
    const { data } = await getIdentityAndTopId();
    //公告弹窗
    if (data.identity == "用户") {
      this.AddAnnouncement();
    }
  },
  components: { Dialog },
  methods: {
    //进入页面获取当前月的第一天到当前日期
    defaultDate() {
				//获取新的时间
				let date = new Date()
				//获取当前时间的年份转为字符串
				let year = date.getFullYear().toString()
				//获取月份，由于月份从0开始，此处要加1，判断是否小于10，如果是在字符串前面拼接'0'
				let month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1).toString() : (date.getMonth() + 1)
					.toString()
				//获取天，判断是否小于10，如果是在字符串前面拼接'0'
				let da = date.getDate() < 10 ? '0' + date.getDate().toString() : date.getDate().toString()
				//字符串拼接，开始时间，结束时间
				let end = year + '-' + month + '-' + da //当天
				let beg = year + '-' + month + '-01' //当月第一天
				this.formData.field103 = [beg, end] //将值设置给插件绑定的数据
        // console.log(this.dateRange+"askndladsaldsla")
			},



     // 表格默认全部，卡片默认成功
     async getList2(row) {
      if (!this.formData.field103) {
        this.formData.field103 = [];
      }
      // 表格默认全部，卡片默认成功
      const param = {
        startTime: this.formData.field103[0], //创建时间
        endTime: this.formData.field103[1], //结束时间
        status: undefined, //提现状态

        userId: this.userId, //用户ID
        signTenantId: sessionStorage.getItem("TenantId") - 0, //租户ID
        // signTenantId:299,  //租户ID
        pageSize: this.queryParams.pageSize,
        pageNum: this.queryParams.pageNum,
      };
      const param2 = {
        startTime: this.formData.field103[0], //创建时间
        endTime: this.formData.field103[1], //结束时间
        status: 'SUCCESS', //提现状态

        userId: this.userId, //用户ID
        signTenantId: sessionStorage.getItem("TenantId") - 0, //租户ID
        // signTenantId:299,  //租户ID
        pageSize: this.queryParams.pageSize,
        pageNum: this.queryParams.pageNum,
      };
      const data = await selectTransactionRecordPaging(param);
      console.log(data, "数据222222");
      if (data.code == 200) {
        this.roleList = data.data.list;
        this.total = data.data.total;
      } else {
        this.$message.error(data.msg);
      }

      const card = await CapWithdrawalRecordStatistics(param2);
      console.log(card, "数据222222");
      if (data.code == 200) {
        this.CardData = card.data;
      } else {
        this.$message.error(data.msg);
      }

      // const card = await CapWithdrawalRecordStatistics(param);
      // if(card.code==200){
      //    this.CardData = card.data;
      // }else{
      //    this.$message.error(data.msg);
      // }

      // console.log(card, "卡片");

      const balance = await selectCapUserWalletById({ userId: this.userId }); //获取账户余额
      if (balance.code == 200) {
        console.log(balance, "当前账户余额");
        this.amountMoney = balance.data.balance;
      } else {
        this.$message.error(balance.msg);
      }
      if (row) {
        this.$message({
          message: "搜索中...",
          type: "success",
        });
      }
    },
    async getList(row) {
      if (!this.formData.field103) {
        this.formData.field103 = [];
      }
     
      const param = {
        startTime: this.formData.field103[0], //创建时间
        endTime: this.formData.field103[1], //结束时间
        status: this.formData.field107 || undefined, //提现状态

        userId: this.userId, //用户ID
        signTenantId: sessionStorage.getItem("TenantId") - 0, //租户ID
        // signTenantId:299,  //租户ID
        pageSize: this.queryParams.pageSize,
        pageNum: this.queryParams.pageNum,
      };
      const data = await selectTransactionRecordPaging(param);
      console.log(data, "数据222222");
      if (data.code == 200) {
        this.roleList = data.data.list;
        this.total = data.data.total;
      } else {
        this.$message.error(data.msg);
      }

      const card = await CapWithdrawalRecordStatistics(param);
      console.log(card, "数据222222");
      if (data.code == 200) {
        this.CardData = card.data;
      } else {
        this.$message.error(data.msg);
      }

      // const card = await CapWithdrawalRecordStatistics(param);
      // if(card.code==200){
      //    this.CardData = card.data;
      // }else{
      //    this.$message.error(data.msg);
      // }

      // console.log(card, "卡片");

      const balance = await selectCapUserWalletById({ userId: this.userId }); //获取账户余额
      if (balance.code == 200) {
        console.log(balance, "当前账户余额");
        this.amountMoney = balance.data.balance;
      } else {
        this.$message.error(balance.msg);
      }
      if (row) {
        this.$message({
          message: "搜索中...",
          type: "success",
        });
      }
    },
    //重置
    resetQuery() {
      this.formData = {
        field103: [],
        field105: undefined,
        mobile: "",
        field104: undefined,
        field106: undefined,
        field107: undefined,
        field108: undefined,
        field109: undefined,
        field110: undefined,
        field111: undefined,
      };

      this.formData.field103[0] =
        this.moment().format("YYYY") +
        "-" +
        this.moment().format("MM") +
        "-" +
        "01" +
        " " +
        "00:00:00";
      this.formData.field103[1] =
        this.moment().format("YYYY-MM-DD") + " " + "23:59:59";
      this.getList2(1);
    },
    //公告弹窗
    AddAnnouncement() {
      //传递子组件当前的路由；然后调用子组件的事件函数
      this.uelLocation = window.location.pathname.slice(1);
      this.$refs.mychild.gitData();
    },
    //提现
    withdrawal() {
      this.$router.push("/finance/userManage/AccountIndex");
      // 跳转到提现页面
    },
    //导出
    async withdrawExport() {
      if (!this.formData.field103) {
        this.formData.field103 = [];
      }
      const param = {
        startTime: this.formData.field103[0], //创建时间
        endTime: this.formData.field103[1], //结束时间
        status: this.formData.field107, //提现状态
        userId: this.userId, //用户ID
        signTenantId: sessionStorage.getItem("TenantId") - 0, //租户ID
        // signTenantId:299,  //租户ID
        pageSize: this.queryParams.pageSize,
        pageNum: this.queryParams.pageNum,
      };
      const res = await exportXls(param);
      console.log(res, "文件流");
      if (!res) return; //
      const excelTitle = "提现记录.xlsx";
      //触发另一个函数

      this.readFileDownload(res, excelTitle);
    },

    //导出函数2
    readFileDownload(data, msg) {
      var res = data;
      if (
        res.type === "application/json" ||
        res.type === "application/json;charset=UTF-8"
      ) {
        // 失败的时候，注意ie兼容问题
        let fileReader = new FileReader();
        fileReader.onload = function (event) {
          let jsonData = JSON.parse(this.result); // this.result是根据event，读取文件后打印的
          console.log(jsonData, "...............");
          if (jsonData.data === null && jsonData.code === 1) {
            Message({
              message: jsonData.msg || "Error",
              type: "error",
              duration: 5 * 1000,
            });
          }
        };
        fileReader.readAsText(res);
      }
      if (
        res.type === "application/octet-stream" ||
        res.type === "application/vnd.ms-excel" ||
        res.type === "application/msexcel" ||
        res.type === "application/vnd.ms-excel;charset=UTF-8"
      ) {
        console.log("success..."); // 成功，注意ie兼容问题

        const blob = new Blob([res], {
          type: "application/vnd.ms-excel;charset=utf-8",
          // type: "application/msexcel;charset=utf-8",
        });

        if (window.navigator && window.navigator.msSaveOrOpenBlob) {
          window.navigator.msSaveOrOpenBlob(blob, msg);
        } else {
          console.log(blob);
          const url = window.URL.createObjectURL(blob);
          console.log(url);
          const aLink = document.createElement("a");
          aLink.style.display = "none";
          aLink.href = url;
          aLink.setAttribute("download", msg);
          document.body.appendChild(aLink);
          aLink.click();
          document.body.removeChild(aLink);
          window.URL.revokeObjectURL(url);
        }
      }
    },

    resetForm() {
      (this.formData = {
        field103: [],
        field105: undefined,
        mobile: "",
        field104: undefined,
        field106: undefined,
        field107: undefined,
        field108: undefined,
        field109: undefined,
        field110: undefined,
        field111: undefined,
      }),
        this.getList();
    },

    // ..分页器
    handleCurrentChange(value) {
      console.log(value, "1");
    },
    handleSizeChange(value) {
      console.log(value, "2");
      this.pageSizes = value;
      console.log(this.pageSizes, "2");
    },
    // ..选择提现类型
    moneyType() {
      // console.log(this.ruleForm.region, "5555555");
      // 1代表支付宝
      if (this.ruleForm.region == "1") {
        gutUserWithdrawalAccountSelectAlipay(this.ruleForm.region).then(
          (res) => {
            this.monetUser = res;
            this.ruleForm.monetUser = this.monetUser[0].id;
          }
        );
      } else {
        selectByPageNumSizeTxList({
          pageNum: 1,
          pageSize: 6,
        }).then((res) => {
          this.monetUser = res.data.list;
          //  console.log( this.monetUser, "3333");
          this.ruleForm.monetUser = this.monetUser[0].id;
        });
        // gutUserWithdrawalAccountSelectBank("1").then((res) => {
        //   console.log(res,'3333')
        //   this.monetUser = res;
        //   console.log(this.monetUser[0].id);
        //   this.ruleForm.monetUser = this.monetUser[0].id;
        // });
      }
    },

    postSelectCapWithdrawalRecordListFun() {
      let objData = { ...this.queryParams };
      objData.userId = this.userId;
      // postSelectCapWithdrawalRecordList(objData).then((data) => {
      //   this.noticeList = data;
      //   this.loading = false;
      // });
    },
  },
};
</script>

<style scoped>
.xhxBox {
  height: 5px;
  border-top: 1px #eee solid;
  margin: 15px 0px 20px 0px;
}
.exportButton {
  /* border: 1px red solid; */
  display: flex;
  justify-content: flex-end;
}
.el-form-item__label {
  font-weight: 500;
}
</style>
<style>
.pay .el-date-editor .el-range-separator {
  width: 15%;
}

.pay .el-card__body {
  height: 100%;
}

.pay .pay-item {
  width: 35%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.pay .pay-item:not(:last-child) {
  border-right: 1px solid #f0f0f0;
}

.pay .pay-item .pay-value {
  font-size: 24px;
  font-weight: bold;
}

.pay .pay-item .pay-value span {
  font-size: 10px;
  margin-right: -5px;
}

.pay .pay-item .value-color {
  color: #3a77f6;
}

.pay .pay-item .pay-label {
  font-size: 11px;
  margin-top: 10px;
}

.pay .el-divider--horizontal {
  background: #f0f0f0;
}

.pay .el-card__header {
  margin: 0 20px;
  padding-left: 0px;
  border: none;
}

.pay .el-tabs__nav-wrap::after {
  height: 0;
}
</style>
